#define _CRT_SECURE_NO_WARNINGS 1


#include "game.h"

void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
	int i = 0;

	for (i = 0; i < rows; i++)
	{
		int j = 0;

		for (j = 0; j < cols; j++)
		{
			board[i][j] = set;
		}

	}

}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	int i = 0;
	printf("--------扫雷--------\n");
	
	for (i = 0; i <= col; i++)
	{
		printf("%d ", i);
	}

	printf("\n");

	for (i = 1; i <= row; i++)
	{
		int j = 0;
		printf("%d ", i);

		for (j = 1; j <= col; j++)
		{
			printf("%c ", board[i][j]);
		}

		printf("\n");
	}

}

void SetMine(char board[ROWS][COLS], int row, int col)
{
	int count = EASY_COUNT;

	while (count)
	{
		int x = rand() % row + 1;
		int y = rand() % col + 1;

		if ('0' == board[x][y])
		{
			board[x][y] = '1';
			count--;
		}

	}
	
}

int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
	return (mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1] + mine[x][y - 1]
		+ mine[x][y + 1] + mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - 8 * '0');
}

void Expand(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y)
{
	
	if ('*' == show[x][y])
	{
		int count = GetMineCount(mine, x, y);

		if (count != 0)
		{
			show[x][y] = count + '0';
		}
		else
		{
			show[x][y] = ' ';
			Expand(mine, show, x - 1, y - 1);
			Expand(mine, show, x - 1, y);
			Expand(mine, show, x - 1, y + 1);
			Expand(mine, show, x, y - 1);
			Expand(mine, show, x, y + 1);
			Expand(mine, show, x + 1, y - 1);
			Expand(mine, show, x + 1, y);
			Expand(mine, show, x + 1, y + 1);
		}

	}
	
}

int IsWin(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
	int i = 0;

	for (i = 1; i <= row; i++)
	{
		int j = 0;

		for (j = 1; j <= col; j++)
		{

			if ('*' == show[i][j] && '0' == mine[i][j])
			{
				return 0;
			}

		}

	}

	return 1;
}

void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
	int x = 0;
	int y = 0;
	int ret = 0;

	while (0 == ret)
	{
		printf("请输入要排查的坐标:>");
		scanf("%d %d", &x, &y);

		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{

			if ('1' == mine[x][y])
			{
				printf("很遗憾，你被炸死了\n");
				DisplayBoard(mine, ROW, COL);
				break;
			}
			else
			{
				Expand(mine, show, x, y);
				DisplayBoard(show, ROW, COL);
				ret = IsWin(mine, show, ROW, COL);
			}

		}
		else
		{
			printf("坐标非法，重新输入\n");
		}

	}

	if (1 == ret)
	{
		printf("恭喜你，排雷成功\n");
		DisplayBoard(mine, ROW, COL);
	}

}